package com.elitesland.security.handle;

import com.elitesland.core.base.ApiCode;
import com.elitesland.core.base.ApiResult;
import com.elitesland.core.exception.BadCaptchaException;
import com.elitesland.core.exception.BadJwtTokenException;
import com.elitesland.core.util.HttpServletResponseUtil;
import lombok.SneakyThrows;
import lombok.val;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <pre>
 * [功能说明]
 * </pre>
 *
 * @author Mir
 * @date 2020/6/24
 */
public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @SneakyThrows
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        val result = ApiResult.fail(ApiCode.AUTHENTICATION_EXCEPTION);

        if (e instanceof InsufficientAuthenticationException) {
            result.setMsg("当前用户没有该操作权限");
        }

        if(e instanceof BadCredentialsException ||
                e instanceof BadCaptchaException){
            result.setMsg(e.getMessage());
        }

        if(e instanceof BadJwtTokenException){
            result.setCode(ApiCode.UNAUTHENTICATED_EXCEPTION.getCode());
            result.setMsg(e.getMessage());
        }

        HttpServletResponseUtil.printJSON(httpServletResponse, result);
    }
}
